package logic

import (
	"context"
	"errors"
	"fmt"
	"math/rand"
	"video-manager/model/cache"
	"video-manager/model/mysql"
	"video-manager/pkg"

	"video-manager/usersrpc/internal/svc"
	"video-manager/usersrpc/usersrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *usersrpc.RegisterRequest) (*usersrpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User

	err := findUser.FindUserByPhoneNum(mysql.DB, in.PhoneNum)
	if err != nil {
		return nil, err
	}
	if findUser.ID != 0 {
		return nil, errors.New("该手机号已注册，可直接登录")
	}

	result, _ := cache.Rdb.Get(l.ctx, "smsCode"+in.PhoneNum).Result()
	if result != in.SmsCode {
		return nil, errors.New("验证码错误，请重新登录")
	}
	user := &mysql.User{
		//Model:          gorm.Model{},
		Phone_num:   in.PhoneNum,
		Pwd:         pkg.MD5(in.PassWord),
		Nick_name:   fmt.Sprintf("游客_%d", rand.Intn(1000)),
		Avatar_link: "http://t4kaiefjz.hn-bkt.clouddn.com/%E5%B1%8F%E5%B9%95%E6%88%AA%E5%9B%BE%202024-06-20%20082208.png",
	}

	if err = user.UserAdd(mysql.DB); err != nil {
		return nil, errors.New("注册失败")
	}
	return &usersrpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
